package com.dingding.manager.modules.dirver.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.exception.bussiness.BussinessException;
import com.dingding.facade.user.common.dto.common.ReqRegisterDriverDTO;
import com.dingding.facade.user.common.dto.special.driver.ReqSpecialDriverId;
import com.dingding.facade.user.common.dto.special.driver.ResSpecialDriver;
import com.dingding.facade.user.dto.common.driver.ReqDriverAuthDTO;
import com.dingding.facade.user.dto.common.driver.ResDriverAuthDTO;
import com.dingding.facade.user.facade.common.driver.IDriverFacade;
import com.dingding.facade.user.facade.special.driver.ISpeicalDriverFacade;
import com.dingding.manager.common.dao.Page;
import com.dingding.manager.core.aop.log.LogRecord;
import com.dingding.manager.core.image.ImageUpload;
import com.dingding.manager.core.shiro.ShiroKit;
import com.dingding.manager.core.shiro.ShiroUser;
import com.dingding.manager.core.util.ToolUtil;
import com.dingding.manager.modules.dirver.dao.DriverManagerDao;
import com.dingding.manager.modules.dirver.dto.ReqAddDriverDTO;
import com.dingding.manager.modules.dirver.dto.ResDriverBasicInfoDTO;
import com.dingding.manager.modules.dirver.dto.RespDetailDriverDTO;
import com.dingding.manager.modules.dirver.dto.RespGetDriverDTO;
import com.dingding.manager.modules.dirver.service.DriverManagerService;
import com.dingding.manager.modules.system.dto.organization.ResOrganizationDTO;
import com.dingding.manager.modules.system.dto.proandcity.ProIdAndCityIdDTO;
import com.dingding.manager.modules.system.service.OrganizationService;
import com.dingding.manager.modules.system.service.ProvinceAndCityService;

/**
 * 
 * @Description: 司机管理业务相关Service
 * @author haoxiaojun
 * @date 2016年12月3日 下午3:48:11
 * @since V 2.5.7
 */	
@Service("driverManagerService")
public class DriverManagerServiceImpl implements DriverManagerService {

	Logger log = Logger.getLogger(this.getClass());

	@Resource(name = "driverManagerDao")
	private DriverManagerDao driverManagerDao;

	// 司机注册认证接口
	@Resource(name = "driverFacade")
	private IDriverFacade driverFacade;

	// 省市级联查询服务
	@Resource(name = "provinceAndCityService")
	private ProvinceAndCityService provinceAndCityService;

	// 专车司机服务接口
	@Resource(name = "speicalDriverFacade")
	private ISpeicalDriverFacade specialDriverFacade;
	
	@Resource(name="organizationService")
	private OrganizationService organizationService;

	/**
	 * 
	 * @Description: 司机管理业务之司机资料编辑
	 * @author haoxiaojun
	 * @return void
	 * @throws Exception
	 * @date 2016年12月3日 下午3:46:59
	 * @since V 2.5.7
	 */
	@LogRecord(moduleName="司机管理",option="修改")
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean editDriver(ReqAddDriverDTO reqAddDriver) {

		if (ToolUtil.isEmpty(reqAddDriver)) {
			return false;
		}

		Boolean driver = driverManagerDao.editDriver(reqAddDriver);

		return driver;

	}

	/**
	 * 
	 * @Description: 司机管理业务之修改司机状态
	 * @author haoxiaojun
	 * @return void
	 * @date 2016年12月3日 下午3:46:49
	 * @since V2.5.7
	 */
	@LogRecord(moduleName="司机管理",option="删除")
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Boolean modifyDriver(String suId, Integer suvStatus) {

		if (ToolUtil.isEmpty(suId) || ToolUtil.isEmpty(suvStatus)) {
			return false;
		}

		return driverManagerDao.modifyDriver(suId, suvStatus);

	}

	/**
	 * 
	 * @Description: 司机管理业务之列表展示司机
	 * @author haoxiaojun
	 * @return List<respGetDriverDto>
	 * @date 2016年12月3日 下午3:46:54
	 * @since V2.5.7
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Page<RespGetDriverDTO> getDriver(Integer start, Integer length, Integer cityId, Integer provice_id,
			Integer companyId, Integer suvStatus,String dvName,String submitTime) {
		if (ToolUtil.isEmpty(start) || ToolUtil.isEmpty(length)) {
			return null;
		}

		// 如果是管理员,返回全部数据
		if (ShiroKit.isManager()) {
			Page<RespGetDriverDTO> driverPage = driverManagerDao.getDriver(start, length, cityId, provice_id, companyId,
					suvStatus, dvName,submitTime);
			return driverPage;
		}
		// 如果是普通用户,返回当前公司所属司机
		if (!ShiroKit.isManager()) {
			Page<RespGetDriverDTO> driverPage = driverManagerDao.getDriver(start, length, null, null, companyId, suvStatus, dvName,submitTime);
			return driverPage;
		}
		return null;
	}

	/**
	 * 
	 * @Description: 司机管理业务之司机详情
	 * @author haoxiaojun
	 * @return void
	 * @date 2016年12月3日 下午3:47:03
	 * @since V2.5.7
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public RespDetailDriverDTO detailDriver(String suid) {

		if (ToolUtil.isEmpty(suid)) {
			return null;
		}

		RespDetailDriverDTO respresult = new RespDetailDriverDTO();
		respresult = driverManagerDao.detailDriver(suid);

		// 如果是专车
		if (respresult.getAuthType() == 2) {
			respresult.setWorkLicenseImage("");
			respresult.setWorkLicenseNumber("");
		}

		// 如果是出租车
		if (respresult.getAuthType() == 3) {
			String workLicenseImage = ImageUpload.imageAddress(respresult.getWorkLicenseImage());
			respresult.setWorkLicenseImage(workLicenseImage);
		}

		// 图片拼接oss地址
		String idCardOpposite = ImageUpload.imageAddress(respresult.getIdCardOppositeImage());
		String idCardPositive = ImageUpload.imageAddress(respresult.getIdCardPositiveImage());
		String jszCopy = ImageUpload.imageAddress(respresult.getJszCopyImage());
		String jsz = ImageUpload.imageAddress(respresult.getJszImage());
		String vehicle = ImageUpload.imageAddress(respresult.getVehicleImage());
		String xszCopy = ImageUpload.imageAddress(respresult.getXszCopyImage());
		String xsz = ImageUpload.imageAddress(respresult.getXszImage());

		// 更改后的图片地址更新到响应Bean
		respresult.setIdCardOppositeImage(idCardOpposite);
		respresult.setIdCardPositiveImage(idCardPositive);
		respresult.setJszCopyImage(jszCopy);
		respresult.setJszImage(jsz);
		respresult.setVehicleImage(vehicle);
		respresult.setXszCopyImage(xszCopy);
		respresult.setXszImage(xsz);

		// 返回
		return respresult;
	}

	/**
	 * 
	 * @Description: 根据公司名称获取公司所有司机Id
	 * @author haoxiaojun
	 * @date 2016年12月8日 下午12:46:05
	 * @since V 2.5.7
	 * @modify by hufan
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public List<String> getDriverUserIdsByConditions(List<Integer> organizationIds, String nameOrPhone) {

		if (ToolUtil.isEmpty(organizationIds)) {
			return null;
		}

		List<String> userIds = new ArrayList<>();

		// 公司id为空返回null
		if (CollectionUtils.isEmpty(organizationIds)) {
			return userIds;
		}

		userIds = driverManagerDao.getDriverUserIdsByConditions(organizationIds, nameOrPhone);
		// 返回
		return userIds;
	}

	/**
	 * 
	 * @Description: 图片上传
	 * @author haoxiaojun
	 * @date 2016年12月9日 下午12:46:09
	 * @since V 2.5.7
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String upLoadImage(String srcImage) throws Exception {

		if (ToolUtil.isEmpty(srcImage)) {
			return null;
		}

		// 获取图片上传工具
		ImageUpload upload = new ImageUpload();

		// 上传图片并返回图片名称
		String fileName = upload.uploadWebPicture(srcImage);
		return fileName;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public ResDriverBasicInfoDTO getResDriverBasicInfoDTOByDriverId(String driverId) {
		return driverManagerDao.getResDriverBasicInfoDTOByDriverId(driverId);
	}

	/**
	 * 
	 * @Description: 司机添加业务
	 * @author haoxiaojun
	 * @date 2016年12月13日 下午4:04:32
	 * @since V 2.5.7
	 */
	@LogRecord(moduleName="司机管理",option="添加")
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean addDriver(ReqDriverAuthDTO reqDriverAuth, String telPhone) throws BussinessException{

		if (ToolUtil.isEmpty(reqDriverAuth) || ToolUtil.isEmpty(telPhone)) {
			return null;
		}
		String userId = null;

		// 获取登录用户信息
		ShiroUser currentLoginUser = ShiroKit.getUser();
		if (ToolUtil.isEmpty(currentLoginUser)) {
			return false;
		}
		// 通过用户信息查询公司Id
		Integer companyId = currentLoginUser.getCompanyId();
		ProIdAndCityIdDTO proIdAndCityId = provinceAndCityService.getProIdAndCityIdByCompanyId(companyId);
		
		/**
		 * @modify: szc  2017-2-7 18:39  根据登录用户添加车辆类型
		 * 如果用户是超级管理员，车辆类型为传入的类型，否则为当前登录用户所在公司的类型
		 */
		
		boolean manager = ShiroKit.isManager();
		if (!manager) {
			//查询机构信息
			ResOrganizationDTO organization = organizationService.getOrganizationById(companyId);
			reqDriverAuth.setAuthType(organization.getOrganizationType());
		}
		
		
		// 设置省份,城市,公司Id
		reqDriverAuth.setCityId(proIdAndCityId.getCityId());
		reqDriverAuth.setOrganizationId(companyId);

		// 创建获取专车司机Id请求Bean
		ReqSpecialDriverId reqSpecialDriverId = new ReqSpecialDriverId();
		// 设置手机号
		reqSpecialDriverId.setTelPhone(telPhone);
		
		// 获取专车用户信息
		ResSpecialDriver resSpecialDriver = specialDriverFacade.getSpecialDriverId(reqSpecialDriverId);

		// 用户不存在 进行司机信息初始化
		if (resSpecialDriver == null || ToolUtil.isEmpty(resSpecialDriver.getSuid())) {

			// 初始化用户信息
			ReqRegisterDriverDTO reqRegisterDriver = new ReqRegisterDriverDTO();
			reqRegisterDriver.setUserName(telPhone);
			userId = driverFacade.registerDriver(reqRegisterDriver);

			if (!ToolUtil.isEmpty(userId)) {
				reqDriverAuth.setUserId(userId);
			}

		} else {
			// 司机存在,设置司机Id,对司机信息进行补充注册
			reqDriverAuth.setUserId(resSpecialDriver.getSuid());
		}

		// 远程调用注册司机服务
		ResDriverAuthDTO auth = null;
		try {
			auth = driverFacade.driverAuth(reqDriverAuth);
		} catch (BussinessException e) {
			throw new com.dingding.manager.common.exception.BussinessException(e.getCode(),e.getMessage());
		}

		if (ToolUtil.isNotEmpty(auth)) {
			return true;
		} else {
			return false;
		}
	}

}
